﻿$(function () {
    $.selectSuggest = function (targetElem, data, dataFunction, itemSelectFunction, layerIframe, defaultValue) {
        if (defaultValue) {
            targetElem.val(defaultValue.name);
            targetElem.attr('data', defaultValue.id);
        } else {
            targetElem.val('');
            targetElem.attr('data', '');
        }

        var target = targetElem[0].id;
        var defaulOption = {
            suggestMaxHeight: '200px', //弹出框最大高度
            itemColor: '#606060', //默认字体颜色
            itemBackgroundColor: 'fff', //默认背景颜色
            itemOverColor: '#ffffff', //选中字体颜色
            itemOverBackgroundColor: '#00b5b1', //选中背景颜色
            itemPadding: 3, //item间距
            fontSize: 12, //默认字体大小
            alwaysShowALL: true //点击input是否展示所有可选项
        };
        var maxFontNumber = 0;//最大字数
        var currentItem;
        var suggestContainerId = target + "-suggest";

        var showClickTextFunction = function () {
            targetElem.val(this.innerHTML);
            targetElem.attr('data', this.id);
            targetElem.attr('target', $(this).attr('target'));
            currentItem = null;
            layerIframe.find(suggestContainer).hide();
        };
        var suggestContainer;
        if (layerIframe.find('#' + suggestContainerId)[0]) {
            suggestContainer = layerIframe.find('#' + suggestContainerId);
            suggestContainer.empty();
        } else {
            suggestContainer = $('<div></div>'); //创建一个子<div>
        }
        suggestContainer.attr('id', suggestContainerId);
        suggestContainer.attr('tabindex', '0');
        suggestContainer.hide();
        var _initItems = function (items) {
            suggestContainer.empty();
            for (var i = 0; i < items.length; i++) {
                if (items[i].name.length > maxFontNumber) {
                    maxFontNumber = items[i].name.length;
                }
                var suggestItem = $('<div></div>'); //创建一个子<div>
                suggestItem.attr('id', items[i].id);
                suggestItem.attr('target', items[i].target);
                suggestItem.append(items[i].name);
                suggestItem.css({
                    'padding': defaulOption.itemPadding + 'px',
                    'white-space': 'nowrap',
                    'cursor': 'pointer'
                });
                suggestItem.bind("mouseover",
                        function () {
                            $(this).addClass('option-seled');
                            currentItem = $(this);
                        });
                suggestItem.bind("mouseout",
                        function () {
                            $(this).removeClass('option-seled');
                            currentItem = null;
                        });
                suggestItem.bind("click", showClickTextFunction);
                suggestItem.bind("click", itemSelectFunction);
                suggestItem.appendTo(suggestContainer);

            }
            suggestContainer.appendTo(layerIframe.find('body'));
        };

        var inputChange = function (newDatas) {
            var inputValue = targetElem.val();
            inputValue = inputValue.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
            var matcher = new RegExp(inputValue, "i");
            return $.grep(newDatas,
                    function (value) {
                        return matcher.test(value.name);
                    });
        };

        // 按键
        var currentSelection = -1;
        targetElem.bind("keyup", function (e) {
            //根据输入显示选项
            if (e.which != 13 && e.which != 38 && e.which != 40) {
                var newDatas = dataFunction ? dataFunction(data) : data;
                _initItems(inputChange(newDatas));
            }

            //按键事件
            var suggestContainerLen = suggestContainer.find('div').length;
            switch (e.which) {
                case 13://enter
                    if (currentItem) {
                        currentItem.trigger("click");
                    }
                    currentItem = null;
                    return;
                    break;
                case 38://up arrow
                    e.preventDefault();
                    $(suggestContainer).children('div').removeClass('option-seled');
                    if ((currentSelection - 1) >= 0) {
                        currentSelection--;
                        $(suggestContainer).children().eq(currentSelection).addClass('option-seled');
                        currentItem = $(suggestContainer).children().eq(currentSelection);
                    } else {
                        currentSelection = -1;
                        $(suggestContainer).children().eq(0).addClass('option-seled');
                        currentItem = $(suggestContainer).children().eq(0);
                    }
                    break;
                case 40://down arrow
                    e.preventDefault();
                    if ((currentSelection + 1) < suggestContainerLen) {
                        $(suggestContainer).children('div').removeClass('option-seled');
                        currentSelection++;
                        $(suggestContainer).children().eq(currentSelection).addClass('option-seled');
                        currentItem = $(suggestContainer).children().eq(currentSelection);
                    }
                    break;
            }
        });
        targetElem.bind("blur", function (e) {
            if (currentItem) {
                currentItem.trigger("click");
                currentItem = null;
            }
        });

        targetElem.unbind("focus").bind("focus", function () {
            var newDatas = dataFunction ? dataFunction(data) : data;
            if (defaulOption.alwaysShowALL) {
                _initItems(newDatas);
            } else {
                _initItems(inputChange(newDatas));
            }
            var suggestContainerWidth = targetElem.innerWidth();
            var suggestContainerLeft = targetElem.offset().left;
            var suggestContainerTop = targetElem.offset().top + targetElem.outerHeight();
//            $('#' + suggestContainerId).removeAttr("style");
            var tempWidth = defaulOption.fontSize * maxFontNumber + 2 * defaulOption.itemPadding + 30;
            var containerWidth = Math.max(tempWidth, suggestContainerWidth);
            layerIframe.find(suggestContainer).css({
                'border': '1px solid #00b5b1',
                'max-height': '200px',
                'top': suggestContainerTop,
                'left': suggestContainerLeft,
                'width': containerWidth,
                'position': 'absolute',
                'font-size': defaulOption.fontSize + 'px',
                'font-family': 'Arial',
                'z-index': 99999,
                'background-color': '#FFFFFF',
                'overflow-y': 'auto',
                'overflow-x': 'hidden',
                'white-space': 'nowrap'

            });
            layerIframe.find(suggestContainer).show();
            windowClick();
        });
//        _initItems(data);

        //点击其它区域，关闭弹出下拉框
        function windowClick() {
            layerIframe.find('body').unbind("click").bind("click", function (e) {
                var clickTarget = $(e.target);
                if (!clickTarget.is(targetElem)) {
                    layerIframe.find(suggestContainer).hide();
                }
            });
        }

        layerIframe.find(suggestContainer).bind("blur", function () {
//            $('#' + suggestContainerId).hide();
            $(this).hide();
        });
    };
});

